package com.xiaoxiong.mami.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xiaoxiong.mami.dao.daomain.Goods;
import com.xiaoxiong.mami.dao.daomain.OrderGoods;
import com.xiaoxiong.mami.dao.daomain.OrderInfo;
import com.xiaoxiong.mami.dao.daomain.UserAddress;
import com.xiaoxiong.mami.http.AppJsonResult;
import com.xiaoxiong.mami.service.*;
import com.xiaoxiong.mami.utils.UUIDUtils;
import com.xiaoxiong.mami.vo.Paginate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;

/**
 * Created by Administrator on 2017/7/27.
 */
@RestController
@RequestMapping("/order")
@Api("订单中心")
public class OrderWeb {


    public static final String YYYY_M_MDD_H_HMM = "yyyyMMddHHmm";
    Logger logger = Logger.getLogger(getClass());


    /* {
                    name: '待确认',
                    _id: 'submitted',
                },
                {
                    name: '已完成',
                    _id: 'finished',
                },
                {
                    name: '已取消',
                    _id: 'canceled',
                },*/


    @Autowired
    GoodsService goodsService;
    @Autowired
    CartService cartService;

    @Autowired
    OrderInfoService orderInfoService;

    @Autowired
    UserAddressService userAddressService;

    @Autowired
    OrderGoodsService orderGoodsService;

    @ApiOperation(value = "获取订单信息", notes = "")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "orderId", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/getOrder", method = RequestMethod.POST)
    public JSONObject getOrderDetail(@RequestParam String orderId) {

        OrderInfo orderInfo = orderInfoService.getOrderByOrderId(orderId);
        if (orderInfo != null){
            JSONObject detail = (JSONObject) JSON.toJSON(orderInfo);
            return AppJsonResult.createSuccessResultStr(detail);
        }
        return AppJsonResult.createErrorResultStr("获取数据失败");
    }



    @ApiOperation(value = "获取订单信息", notes = "")
    @RequestMapping(value = "/updateOrder/{userId}", method = RequestMethod.POST)
    public JSONObject updateOrder(@PathVariable String userId,@RequestParam String orderId,@RequestParam String orderStatus) {

        String statusName = "处理中";
        switch (orderStatus){
            case "finished":
                statusName = "已完成";
                break;
            case "canceled":
                statusName = "已取消";
                break;
        }
        int result = orderInfoService.updateStatusByOrderId(orderId, orderStatus,statusName);
        if (result == 1){
            return AppJsonResult.createSuccessResultStr(null);
        }
        return AppJsonResult.createErrorResultStr("更新订单信息失败");
    }



    @RequestMapping(value = "/getOrderList", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject getOrderList(@RequestParam String orderStatus, @RequestParam int page, @RequestParam int limit) {
        int start = 0;
        int end = limit * page;
        if (page > 0) {
            start = (page - 1) * limit;
            end = (page) * limit;
        }
        List<OrderInfo> orderInfoList;

        orderInfoList = orderInfoService.getOrderListByStatusLimit(orderStatus,start,limit);
        int total;
        JSONArray orderJsonArray = new JSONArray();
        if (orderInfoList != null) {
            switch (orderStatus){
                case "finished":
                case "canceled":
                    Collections.reverse(orderInfoList);
                    break;
            }
            orderJsonArray = (JSONArray) JSONArray.toJSON(orderInfoList);
        }
        total = orderInfoService.getOrderCountStatus(orderStatus);
        for (int i = 0; i < orderJsonArray.size(); i++) {
            JSONObject item = orderJsonArray.getJSONObject(i);
            String orderId = item.getString("orderId");
            List<OrderGoods> goodsList = orderGoodsService.getGoodsByOrderIds(orderId);
            JSONArray goodsListJson = (JSONArray) JSONArray.toJSON(goodsList);
            item.put("orderGoods",goodsListJson);
        }

        int allTotal = total;

        JSONObject data = new JSONObject();
        data.put("total", total);
        if (allTotal - end > 0) {
            data.put("hasNext", "1");
            data.put("nextPage", page+1);
        }else {
            data.put("hasNext", "0");
            data.put("nextPage",page);
        }
        data.put("orderList", orderJsonArray);
        return AppJsonResult.createSuccessResultStr(data);
    }
}
